<!--
  冻结余额对话框组件
  @description 商户余额冻结/解冻功能的对话框组件
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
    <div v-loading="loading">
      <!-- 余额信息展示 -->
      <el-descriptions :column="2" border class="mb-20px" v-if="balanceData">
        <el-descriptions-item :label="t('settle.balance.merchantNo')">
          {{ balanceData.merchantNo }}
        </el-descriptions-item>
        <el-descriptions-item :label="t('settle.balance.merchantName')">
          {{ balanceData.merchantName }}
        </el-descriptions-item>
        <el-descriptions-item :label="t('settle.balance.availableBalance')">
          <span class="available-text">¥{{ (balanceData.availableBalance / 100).toFixed(2) }}</span>
        </el-descriptions-item>
        <el-descriptions-item :label="t('settle.balance.frozenBalance')">
          <span class="frozen-text">¥{{ (balanceData.frozenBalance / 100).toFixed(2) }}</span>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 操作表单 -->
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item
          :label="
            operationType === 'freeze'
              ? t('settle.balance.freezeAmount')
              : t('settle.balance.unfreezeAmount')
          "
          prop="amount"
        >
          <el-input-number
            v-model="formData.amount"
            :placeholder="
              operationType === 'freeze'
                ? t('settle.balance.rules.freezeAmountRequired')
                : t('settle.balance.rules.unfreezeAmountRequired')
            "
            :min="0.01"
            :max="maxAmount"
            :precision="2"
            :step="0.01"
            style="width: 100%"
          />
          <div class="form-tip">
            {{
              operationType === 'freeze'
                ? t('settle.balance.maxFreezeAmount')
                : t('settle.balance.maxUnfreezeAmount')
            }}: ¥{{ maxAmount.toFixed(2) }}
          </div>
        </el-form-item>

        <el-form-item
          :label="
            operationType === 'freeze'
              ? t('settle.balance.freezeReason')
              : t('settle.balance.unfreezeReason')
          "
          prop="reason"
        >
          <el-select
            v-model="formData.reason"
            :placeholder="
              operationType === 'freeze'
                ? t('settle.balance.rules.freezeReasonRequired')
                : t('settle.balance.rules.unfreezeReasonRequired')
            "
            style="width: 100%"
          >
            <el-option
              v-for="(label, value) in reasonOptions"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="t('settle.balance.operationDesc')" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :placeholder="t('settle.common.pleaseInput') + t('settle.balance.operationDesc')"
            :rows="4"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="loading">
        {{ t('settle.common.confirm') }}
      </el-button>
      <el-button @click="dialogVisible = false">
        {{ t('settle.common.cancel') }}
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { freezeMerchantBalanceApi, unfreezeMerchantBalanceApi } from '@/api/settle/balance'
import type { BalanceVO, FreezeBalanceReqVO, UnfreezeBalanceReqVO } from '@/api/settle/types'
import { Dialog } from '@/components/Dialog'

defineOptions({ name: 'FreezeBalanceDialog' })

const { t } = useI18n()

// 弹窗相关
const dialogVisible = ref(false)
const loading = ref(false)
const operationType = ref<'freeze' | 'unfreeze'>('freeze')

// 余额数据
const balanceData = ref<BalanceVO>()

// 表单相关
const formRef = ref<FormInstance>()
const formData = ref({
  merchantNo: '',
  amount: 0,
  reason: '',
  description: ''
})

// 计算属性
const dialogTitle = computed(() => {
  return operationType.value === 'freeze'
    ? t('settle.balance.freeze')
    : t('settle.balance.unfreeze')
})

const maxAmount = computed(() => {
  if (!balanceData.value) return 0
  return operationType.value === 'freeze'
    ? balanceData.value.availableBalance / 100
    : balanceData.value.frozenBalance / 100
})

const reasonOptions = computed(() => {
  if (operationType.value === 'freeze') {
    return {
      RISK_CONTROL: t('settle.balance.freezeReasons.riskControl'),
      DISPUTE: t('settle.balance.freezeReasons.dispute'),
      VIOLATION: t('settle.balance.freezeReasons.violation'),
      MANUAL: t('settle.balance.freezeReasons.manual'),
      OTHER: t('settle.balance.freezeReasons.other')
    }
  } else {
    return {
      RISK_RESOLVED: t('settle.balance.unfreezeReasons.riskResolved'),
      DISPUTE_RESOLVED: t('settle.balance.unfreezeReasons.disputeResolved'),
      VIOLATION_RESOLVED: t('settle.balance.unfreezeReasons.violationResolved'),
      MANUAL: t('settle.balance.unfreezeReasons.manual'),
      OTHER: t('settle.balance.unfreezeReasons.other')
    }
  }
})

// 表单校验规则
const formRules = reactive<FormRules>({
  amount: [
    { required: true, message: t('settle.balance.rules.amountRequired'), trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error(t('settle.balance.rules.amountMin')))
        } else if (value > maxAmount.value) {
          callback(new Error(t('settle.balance.rules.amountMax')))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  reason: [{ required: true, message: t('settle.balance.rules.reasonRequired'), trigger: 'change' }]
})

// 事件定义
const emit = defineEmits(['success'])

/**
 * 打开对话框
 */
const open = (balance: BalanceVO, type: 'freeze' | 'unfreeze') => {
  dialogVisible.value = true
  operationType.value = type
  balanceData.value = balance
  resetForm()
  formData.value.merchantNo = balance.merchantNo
  formData.value.amount = maxAmount.value
}

/**
 * 提交操作
 */
const submitForm = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return

  loading.value = true
  try {
    const data = { ...formData.value }
    // 将元转换为分
    data.amount = Math.round(data.amount * 100)

    if (operationType.value === 'freeze') {
      await freezeMerchantBalanceApi(balanceData.value!.merchantNo, data.amount, data.remark)
      ElMessage.success(t('settle.balance.tips.freezeSuccess'))
    } else {
      await unfreezeMerchantBalanceApi(balanceData.value!.merchantNo, data.amount, data.remark)
      ElMessage.success(t('settle.balance.tips.unfreezeSuccess'))
    }

    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('操作余额失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 重置表单
 */
const resetForm = () => {
  formData.value = {
    merchantNo: '',
    amount: 0,
    reason: '',
    description: ''
  }
  formRef.value?.resetFields()
}

// 暴露方法
defineExpose({ open })
</script>

<style scoped>
.mb-20px {
  margin-bottom: 20px;
}

.available-text {
  color: #67c23a;
  font-weight: bold;
  font-size: 16px;
}

.frozen-text {
  color: #e6a23c;
  font-weight: bold;
  font-size: 16px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>
